import os
from datetime import date
from decimal import Decimal
import pandas as pd

from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import sessionmaker, declarative_base

from backend.db.base import Base
from backend.models.member import Member, MemberCertificate

# 获取当前文件的绝对路径（假设这段代码在 vip/backend 目录下的某个文件中）
current_dir = os.path.dirname(os.path.abspath(__file__))
# 构造数据库文件的绝对路径（指向 vip/backend/db/test.db）
print(current_dir)
db_path = os.path.join(current_dir, "test.db")
# 生成 SQLite 连接字符串
SQLITE_DATABSE_URL = f"sqlite:///{db_path}"
# 确保 db 目录存在
os.makedirs(os.path.dirname(db_path), exist_ok=True)

engine = create_engine(SQLITE_DATABSE_URL, connect_args={"check_same_thread": False}, echo=True)
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)


def get_yield_session():
    """获取session"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def create_table():
    """创建表"""
    try:
        from backend.models import member, member_transaction
        Base.metadata.create_all(bind=engine)
    except Exception as e:
        print(f'创建失败{e}')


def drop_table():
    """删除所有表"""
    Base.metadata.drop_all(bind=engine)


def print_table_name():
    """展示已创建的表名"""
    inspector = inspect(engine)
    tables = inspector.get_table_names()
    print("数据库中的表：", tables)


def export_member():
    df = pd.read_sql_table("member", con=engine)
    return  df


def export_member_certificate():
    df = pd.read_sql_table("member_certificate", con=engine)
    return df


def export_transaction():
    df = pd.read_sql_table("Transaction", con=engine)
    return df


if __name__ == "__main__":
    create_table()
    print_table_name()
